package com.hc.controller;

import com.hc.common.bean.Result;
import com.hc.common.bean.ResultUtil;
import com.hc.common.enums.ResultEnum;
import com.hc.common.utils.EmailUtil;
import com.hc.common.utils.StringUtil;
import com.hc.common.utils.VerifyCodeUtil;
import com.hc.common.utils.encode.Base64Util;
import com.hc.domain.User;
import com.hc.domain.VerifyCode;
import com.hc.ex.GlobalException;
import com.hc.query.UserRegistVO;
import com.hc.service.UserService;
import com.hc.trans.UserTrans;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author 舞遍邓城一条街
 * @description
 * @Date 2021/11/25 11:39
 */
@Slf4j
@Controller
@RequestMapping("/account")
public class AccountController {

    @Resource
    private UserService userService;


    @ResponseBody
    @PostMapping("/selectUserByAccount")
    public Result selectUserByAccount(String account) {
        boolean accountExists = userService.isAccountExists(account);
        if (accountExists) {
            return ResultUtil.fail().setMsg("该用户名已注册");
        }
        return ResultUtil.success().setMsg("该用户名可以使用");
    }


    @ResponseBody
    @GetMapping("/getVerifyCode")
    public void getVerifyCode(HttpSession session, HttpServletResponse response) {
        //生成验证码
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
        System.out.println("verifyCode  " + verifyCode);
        //验证码放入session
        session.setAttribute("verifyCode", verifyCode);
        //验证码存入图片
        response.setContentType("image/png");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            VerifyCodeUtil.outputImage(105, 45, outputStream, verifyCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @GetMapping("/checkVerifyCode")
    public Result checkVerifyCode(String verifyCode, HttpSession session, HttpServletResponse response) {
        System.out.println("verifyCode  " + verifyCode);
        //验证码放入session
        Object verifyCode0 = session.getAttribute("verifyCode");
        System.out.println(verifyCode0);
        if (verifyCode == null || verifyCode0 == null) {
            return ResultUtil.fail().setMsg("Session中不存在验证码");
        }
        if (verifyCode.equalsIgnoreCase(verifyCode0.toString())) {
            return ResultUtil.success().setMsg("验证码正确");
        } else {
            return ResultUtil.fail().setMsg("验证码不正确");
        }
    }

    /**
     * 用户注册
     *
     * @param userRegistVO
     * @param mav
     * @return
     */
    @ResponseBody
    @PostMapping("/regist")
    public Result regist(@Valid UserRegistVO userRegistVO) {

        User user = UserTrans.MAPPER.UserRegistVO2User(userRegistVO);

        //未激活状态
        user.setStatus(3);
        //生成随机的盐值
        String salt = StringUtil.genString(19);
        user.setSalt(salt);
        user.setAvatar("http://bing-images.oss-cn-beijing.aliyuncs.com/aa/bb/male1638154958151.jpg");
        //对用户密码进行加密
        final String encodedPassword = Base64Util.encode(user.getPassword());
        user.setPassword(encodedPassword);

        int insertRes = userService.insert(user);
        if (insertRes > 0) {
            //给用户邮箱发送激活邮件
            String subject = "来自阿里的激活邮箱";
            //直接将盐值当成激活码
            String content = "点击如下连接激活账户，如果不能点击请复制到浏览器地址栏访问：" +
                    "http://www.wego.com:8080/projshow/account/activeUser?code=" + Base64Util.encode(salt);
            EmailUtil.send(userRegistVO.getEmail(), subject, content);

            return ResultUtil.success().setMsg("注册成功，请打开邮箱激活！");
        } else {
            return ResultUtil.fail().setMsg("注册失败");
        }
    }

    @GetMapping("/activeUser")
    public ModelAndView activeUser(String code, ModelAndView mav, HttpSession session) {
        String salt = Base64Util.decode(code);
        User user = userService.selectBySalt(salt);

        if (code == null) {
            throw new GlobalException(500, "验证码错误");
        }
        int updateRes = userService.updateUserStatusByCode(salt);
        if (updateRes != 1) {
            throw new GlobalException(500, "激活失败");
        }
        session.setAttribute("loginUser", user);
        mav.setViewName("user/index");
        return mav;
    }

    /**
     * 用户登录
     *
     * @param user
     * @param session
     * @return
     */
    @ResponseBody
    @GetMapping("/login")
    public Result login(User user, HttpSession session, HttpServletRequest request, @RequestParam("verification") String verification) {
        boolean flag = true;
        String account = user.getAccount();
        String password = user.getPassword();
        String code = (String) session.getAttribute("verifyCode");
        if (!(verification.equalsIgnoreCase(code))) {
            return ResultUtil.fail(ResultEnum.NICE);

        }
        if (account != null && !account.equals("") && password != null && !password.equals("")) {
            // 根据登录名查找 用户信息
            User loginUser = userService.selectByAccount(account);
            if (loginUser == null) {
                flag = false;
            }
            // 对比 数据库中密码

            String pwd = Base64Util.encode(password);
            flag = pwd.equals(loginUser.getPassword());


            if (flag) {
                // 登录用户信息 放入 session
                session.setAttribute("loginUser", loginUser);
                // 进入主页面
                return ResultUtil.success();
            } else {
                return ResultUtil.fail(ResultEnum.ERROR_ACCOUNT_PASSWORD);
            }

        }
        return ResultUtil.fail(ResultEnum.ERROR);
    }



    /**
     * 访问首页
     */
    @GetMapping("/index")
    public String index() {
        return "/user/index";
    }

}